#!/usr/bin/env node

const program = require('./js/dialog').commander();
const utils = require('./js/utils');
const fs = require('fs-extra');
const path = require('path');
// const executablePath = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const executablePath = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe';

function getCookies(url, isEdge) {
    return new Promise(resolve => {
        require(isEdge ? './edge-cookies-secure.js' : 'chrome-cookies-secure').getCookies(url, 'puppeteer', function (err, cookies) {
            resolve(cookies);
        });
    });
}
async function autoScroll(page) {
    return page.evaluate(() => {
        return new Promise((resolve, reject) => {
            //滚动的总高度
            var totalHeight = 0;
            //每次向下滚动的高度 100 px
            var distance = 100;
            var timer = setInterval(() => {
                //页面的高度 包含滚动高度
                var scrollHeight = document.body.scrollHeight;
                //滚动条向下滚动 distance
                window.scrollBy(0, distance);
                totalHeight += distance;
                //当滚动的总高度 大于 页面高度 说明滚到底了。也就是说到滚动条滚到底时，以上还会继续累加，直到超过页面高度
                if (totalHeight >= scrollHeight) {
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        })
    });
}
async function screenshot({ url, width, height, file, selector, value, open, devtools, wait, edge }) {
    width = +(width || 1920);
    height = +(height || 900);
    console.log("[screenshot]: ", { url, width, height, file, selector, value, open, devtools, wait, edge });

    const browser = await require('puppeteer').launch({
        headless: !open, // 开启界面
        devtools: devtools, // 开启调试
        executablePath,
    });
    const page = await browser.newPage();
    await page.setCookie(...await getCookies(url, edge));
    await page.setViewport({ width, height });
    await page.goto(url);
    wait && await utils.sleep(wait * 1000);

    if (value) {
        const list = value.split(';');
        for (const item of list) {
            const [el, v] = item.split(':');
            await page.waitForSelector(el);
            if (v === 'click') {
                await page.click(el);
            } else if (v !== undefined) {
                await page.type(el, v);
            }
        }
    }

    let target = page;
    if (selector) {
        await page.waitForSelector(selector);
        target = await page.$(selector);
    }
    await autoScroll(page);
    await target.screenshot({ path: file });
    await page.close();
    await browser.close();
}

// xss -u http://localhost:1112/xs_gateway/login -f xs.jpg -v "input[name='username']:admin;input[name='password']:123456;button:click"
// xss -u https://www.baidu.com/ -w 1000 -i 2000 -f 3.png -e -o -t
function main() {
    program
        .version('1.0.0')
        .option('-u, --url <http://my.com>', 'url')
        .option('-w, --width <1920>', 'width')
        .option('-i, --height <900>', 'height')
        .option('-f, --file <dist.jpg>', '目标文件', '1.jpg')
        .option('-s, --selector [#main]', '截图的目标selector, 可选，不设置则截图body')
        .option('-v, --value [selector:value;[...]]', '设置selector的value')
        .option('-o, --open', '显示浏览器')
        .option('-t, --devtools', '打开调试器')
        .option('-r, --wait [3]', '等待x秒', 0)
        .option('-e, --edge', '生成edge-cookies-secure')
        .parse(process.argv);

    let { url, width, height, file, selector, value, open, devtools, wait, edge } = program;
    if (edge) {
        if (!fs.existsSync(path.join(__dirname, 'edge-cookies-secure.js'))) {
            const script = fs.readFileSync(path.join(__dirname, 'node_modules', 'chrome-cookies-secure', 'index.js'), 'utf-8');
            fs.writeFileSync(path.join(__dirname, 'edge-cookies-secure.js'), script.replaceAll('Google', 'Microsoft').replaceAll('Chrome', 'Edge'));
        }
    }
    if (!url) {
        console.log("没有url");
        process.exit(0);
    }
    screenshot({ url, width, height, file, selector, value, open, devtools, wait, edge });
}

main();
